<template>
	<div class="content-box">
		<el-row :gutter="10" class="head-row">
			<el-col :span="20" class="firstcol">
				<el-button disabled style="margin-right: 0.625rem;" type="text">根据日期筛选数据</el-button>
				<el-date-picker v-model="startDate" type="date" placeholder="开始日期" style="margin-right: 0.625rem;"
					clearable @change="changeStart">
				</el-date-picker>
				<el-date-picker v-model="endDate" type="date" placeholder="结束日期" clearable
					style="margin-right: 0.625rem;" @change="changeEnd">
				</el-date-picker>
			</el-col>
			<el-col :span="2">
				<el-button class="btn" @click="handleDao" type="success">导出excel</el-button>
			</el-col>
		</el-row>



		<div class="ceshibox">

			<div v-if="tableData.length">
				<vxe-table resizable show-overflow ref="xTree2" keep-source :sync-resize="selectTab"
					:tree-config="{ children: 'children', showIcon: 'true', expandAll: 'true', reserve: true }"
					@cell-click="cellClickEvent" @edit-closed="kkk" highlight-current-row
					:edit-config="{ trigger: 'click', mode: 'cell', activeMethod: activeCellMethod }" :data="tableData">
					<vxe-table-column type="seq" width="60"></vxe-table-column>
					<vxe-table-column field="name" title="类目" tree-node width="200" height="300">

					</vxe-table-column>

					<!-- <vxe-table-colgroup v-for="(item, index) in placelist" :title="item.name" :key="index"> -->
					<vxe-table-column v-for="(item, index) in placelist" :title="item.name" :field="'maindata[' + index + '].money'"
						:edit-render="{ name: 'input' }">
					</vxe-table-column>
					<!-- <vxe-table-column title="数量" :field="'maindata[' + index + '].num'"
							:edit-render="{ name: 'input' }">
						</vxe-table-column> -->
					<!-- </vxe-table-colgroup> -->


					<vxe-table-column title="预算、测算总金额" field="predict_money">
					</vxe-table-column>
					<!-- <vxe-table-column title="预算、测算总工程量" field="predict_do">
					</vxe-table-column> -->
					<!-- <vxe-table-column title="动态累计发生工程量汇总" field="total_num">
					</vxe-table-column> -->
					<vxe-table-column title="动态累计发生金额" type="number" field="total_money">
						<template v-slot="{ row }">
							<span>{{ totalmoney(row) }} 元</span>
						</template>
					</vxe-table-column>
					<!-- <vxe-table-column title="剩余工程量" field="over_do">
						<template v-slot="{ row }">
							<span>{{ leaveNum(row) }}</span>
						</template>
					</vxe-table-column> -->
					<vxe-table-column title="剩余金额" field="over_money">
						<template v-slot="{ row }">
							<span>{{ leaveAmount(row) }} 元</span>
						</template>
					</vxe-table-column>
					<vxe-table-column title="备注" field="remarks.remark" :edit-render="{}">
						<template #edit="{ row }">
							<vxe-input v-model="row.remarks.remark" type="text" @blur="changeRemark(row.remarks)">
							</vxe-input>
						</template>
					</vxe-table-column>
				</vxe-table>
			</div>
			<div v-else style="text-align:center;font-size:7vh;color:gray">该时段数据为空</div>
		</div>
	</div>
</template>

<script>
import {
	getArticalData,
	UpdateArticalData,
	UpdateRemarkData
} from "../../api/article";
const XEUtils = require('xe-utils')
export default {
	name: "VueElementAdminIndex",
	data() {
		return {
			pickerOptions0: {
				disabledDate: time => {
					if (this.startDate) {
						return time.getTime() < this.startDate
					}
				}
			},
			end_Date: {
				disabledDate: time => {
					if (this.startDate) {
						return time.getTime() <= this.startDate
					}
				}
			},
			showheader: "false",
			smallActive: "tujian",
			tabPosition: "top",
			keyword: "",
			moduleslist: [],
			keyword: "",
			tableData: [],
			// tableDataC: [],
			placelist: [],
			pid: 15,
			selectTab: '',
			isShow: false,
			tableData1: [],
			startDate: '',
			endDate: '',
			currentDate: new Date(),
			rowData: [],
			nameDisabled: false,
			upData: [],		//旧的数据，用于比较新旧数据，避免不必要的请求。	

		};
	},
	created() {
		var pro_id = this.$route.query.project_id
		this.pid = pro_id
		this.startDate = this.dealTime(new Date())
		this.endDate = this.startDate
		this.getData();

	},
	mounted() {
		var pro_id = this.$route.query.project_id
		this.pid = pro_id
	},
	methods: {
		//修改备注
		async changeRemark(res) {
			await UpdateRemarkData(res)
		},
		//禁止编辑
		activeCellMethod({ row, rowIndex }) {
			console.log('Bianji', row);
			this.upData = []
			row.maindata.forEach((res) => {
				this.upData.push({ ...res })
			})
			// if (row.level == 1) {
			if (row.children !== undefined) {
				this.$XModal.message({
					message: '禁止编辑',
					status: 'error'
				})
				return false
			}

			if (this.startDate != this.endDate || this.startDate > this.dealTime(this.currentDate)) {
				console.log(this.startDate, this.dealTime(this.currentDate))
				this.$XModal.message({
					message: '禁止编辑，确保表单时间范围为一天',
					status: 'error'
				})
				return false
			}
			// if (row.level == 2 && row.children !== undefined) {
			// 	return false
			// }
			return true
		},
		// //数据合并
		countAmount(row) {
			return XEUtils.sum(row.maindata, 'money')
		},
		leaveAmount(row) {
			// let newresult = Number(row.predict_money) - Number(this.totalmoney(row))
			let newresult = Number(row.totalmoney)
			return newresult.toFixed(2)
		},

		//材料表相关
		totalnum(row) {
			return XEUtils.sum(row.maindata, 'num')
		},
		totalmoney(row) {
			return XEUtils.sum(row.maindata, 'money')
		},
		leaveNum(row) {
			// let newresult = Number(row.predict_do) - Number(row.total_num)
			let newresult = Number(row.totalnum)
			return newresult
		},
		//获取当日数据
		getCurrentData() {
			this.getData()
		},
		//点击单元格触发@cell-click="cellDown"
		cellClickEvent(row) {
			console.log(row);
			this.rowData = row.row.maindata
		},
		//单元格失去焦点时修改
		async kkk(row, rowIndex) {
			const arr = this.rowData
			let list = row.row.maindata
			var objNum = {}
			var isExist = false;
			console.log(this.upData, "uouououououo	")
			for (var i = 0; i < list.length; i++) {
				var obj = list[i];
				var money = obj.money;
				var num = obj.num;
				// var isExist = false;
				// console.log(this.upData)
				for (var j = 0; j < this.upData.length; j++) {
					if (this.upData[i].money != money || this.upData[i].num != num) {
						const res = await UpdateArticalData(obj)
						if (res.code === 200) {
							isExist = true
						}
					}
					// var aj = arr[j];
					// var n = aj.money;
					// if (n == money) {
					// 	isExist = true; 
					// 	break;
					// }
					// objNum = obj
				}
			}
			if (isExist) {
				this.getData()

			}
			// console.log(list);
			// const res = await UpdateArticalData(objNum)
			// if (res.code === 200) {
			// 	return this.$message.success('修改成功')
			// }
		},
		//初始获取数据
		async getData() {
			// if(this.endDate ==''){
			// 	const res = await getArticalData({
			// 		project_id: this.pid,
			// 		day_id:currentDate
			// 	});
			// }
			const res = await getArticalData({
				project_id: this.pid,
				start_day: this.startDate,
				end_day: this.endDate,
				day_id: '',

			});
			console.log(res.moduleslist)


			var templist = JSON.parse(JSON.stringify(res.moduleslist))		//字段表
			this.gettotal = (aimlist) => {
				aimlist.map((res5) => {
					res5.totalnum = Number(res5.predict_do) - Number(res5.totalnum)
					res5.totalmoney = Number(res5.predict_money) - Number(res5.totalmoney)
					// if(res5.children){
					// 	gettotal(res5.children)
					// }
				})
			}
			this.gettotal(templist)

			var temp = []			//总造价
			var total_predict_do = 0
			var total_predict_money = 0
			var total_over_do = 0
			var total_over_money = 0
			var total_num = 0
			var total_num2 = 0
			var totalSquare = 0
			var total_totalmoney = 0
			var total_totalnum = 0
			res.placelist.forEach((res) => {
				if (res.square) {
					totalSquare += (res.square)
				}
			})
			templist.forEach((item, index) => {

				if (item.predict_do) {
					total_predict_do += item.predict_do
				}
				if (item.predict_money) {
					total_predict_money += item.predict_money
				}
				if (item.over_do) {
					total_over_do += item.over_do
				}
				if (item.over_money) {
					total_over_money += item.over_money
				}
				if (item.totalmoney) {
					total_totalmoney += item.totalmoney
				}
				if (item.totalnum) {
					total_totalnum += item.totalnum
				}

				if (!index) {
					temp = item.maindata
				} else {
					for (var i = 0; i < temp.length; i++) {
						if (item.maindata[i].money) {

							if (item.maindata[i].num) {
								total_num += item.maindata[i].num
								total_num2 += item.maindata[i].num / res.placelist[i].square
								// temp[i].money = Number(temp[i].money) + Number(item.maindata[i].num) * Number(item.maindata[i].money)
								temp[i].money = Number(temp[i].money) + Number(item.maindata[i].money)
							} else {
								temp[i].money = Number(temp[i].money) + Number(item.maindata[i].money)
							}
						}
					}
				}
			})
			this.placelist = res.placelist
			var tempa = JSON.parse(JSON.stringify(temp))		//总造价指标
			this.placelist.forEach((res, index) => {
				tempa[index].money = temp[index].money / Number(res.square)
			})

			var restemp = []
			res.moduleslist.forEach((module) => {
				let module2 = JSON.parse(JSON.stringify(module.maindata))
				module2.map((res) => { res.money = res.money / totalSquare; res.num = res.num / totalSquare; })
				restemp.push({ name: module.name + "总计造价", maindata: module.maindata, predict_do: module.predict_do, predict_money: module.predict_money, total_num: module.totalnum, total_money: module.totalmoney, totalnum: module.predict_do - module.totalnum, totalmoney: module.predict_money - module.totalmoney })
				restemp.push({ name: module.name + "总计单方造价（指标）", maindata: module2, predict_do: module.predict_do / totalSquare, predict_money: module.predict_money / totalSquare, total_num: module.totalnum / totalSquare, total_money: module.totalmoney / totalSquare, totalnum: (module.predict_do - module.totalnum) / totalSquare, totalmoney: (module.predict_money - module.totalmoney) / totalSquare })
				// restemp.push({ name: module.name+"总计单方造价（指标）", maindata: tempa,predict_do:(total_predict_do/totalSquare).toFixed(2), predict_money:(total_predict_money/totalSquare).toFixed(2),total_num:total_num2,totalnum:(total_totalnum/totalSquare).toFixed(2),totalmoney:(total_totalmoney/totalSquare).toFixed(2) })
			})
			this.moduleslist = ["总计造价", "总计单方造价（指标）"]
			for (var i = 0; i < 2; i++) {
				if (i == 0) {
					restemp.push({ name: this.moduleslist[i], maindata: temp, predict_do: total_predict_do, predict_money: total_predict_money, over_do: total_over_do, over_money: total_over_money, total_num, totalnum: total_totalnum, totalmoney: total_totalmoney })
				} else {
					restemp.push({ name: this.moduleslist[i], maindata: tempa, predict_do: (total_predict_do / totalSquare).toFixed(2), predict_money: (total_predict_money / totalSquare).toFixed(2), total_num: total_num2, totalnum: (total_totalnum / totalSquare).toFixed(2), totalmoney: (total_totalmoney / totalSquare).toFixed(2) })
				}
			}
			this.tableData = restemp

			var showDetail = (totalList) => {
				totalList.map((item) => {
					item["count_Amount"] = this.countAmount(item)
					item["over_money"] = this.leaveAmount(item)
					item["total_do"] = this.totalnum(item)
					item["total_money"] = this.totalmoney(item)
					item["over_do"] = this.leaveNum(item)
					if (item.children) {
						showDetail(item.children)
					}
				})
			}
			showDetail(restemp)

			if (res.moduleslist.length && !this.selectTab) {
				this.selectTab = res.moduleslist[0].id
			}
			this.$refs.xTree.forEach((res) => {
				this.$nextTick(() =>
					res.setAllTreeExpand(true)
				)
			})
			this.$refs.xTree2.forEach((res) => {
				this.$nextTick(() =>
					res.setAllTreeExpand(true)
				)
			})

		},

		changeTab() {
			this.$refs.xTree.forEach((res) => {
				this.$nextTick(() =>
					res.setAllTreeExpand(true)
				)
			})
			this.$refs.xTree2.forEach((res) => {
				this.$nextTick(() =>
					res.setAllTreeExpand(true)
				)
			})
		},

		//将date类型的数据处理成yyyy-mm-dd类型的数据
		dealTime(res) {
			var dateList = {
				y: res.getFullYear(),
				M: res.getMonth() + 1,
				d: res.getDate(),
			}
			if (String(dateList["M"]).length == 1) {
				dateList["M"] = '0' + dateList["M"]
			}
			if (String(dateList["d"]).length == 1) {
				dateList["d"] = '0' + dateList["d"]
			}
			return dateList["y"] + "-" + dateList["M"] + "-" + dateList["d"]
		},

		changeStart(res) {
			if (!res) {
				this.startDate = ""
				this.getData()
				return false
			}
			this.startDate = this.dealTime(res)
			this.getData()
		},
		changeEnd(res) {
			if (!res) {
				this.endDate = ""
				this.getData()
				return false
			}
			this.endDate = this.dealTime(res)
			this.getData()
		},

		handleDao() {
			console.log(this.$refs.xTree2, "ssssss")
			this.$refs.xTree2.exportData({
				filename: "统计",
				type: "xlsx",
				useStyle: true,
				data: this.exportData
			})
		}
	},
	computed: {

	}
};
</script>

<style lang="scss" scoped>
.content-box {
	width: 100%;

	.content-table {
		width: 96%;
		margin: 0 auto;
		margin-bottom: 1.25rem;
	}

	.head-row {
		margin-top: 1.25rem;
		margin-left: 1.75rem;
		margin-bottom: 1.25rem;

		.el-col {
			margin-left: 1.75rem;
		}
	}

	.upplace {
		padding: 5px 0
	}
}
</style>
